package com.next

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class ProjectController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def springSecurityService

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def projectList
        def count
        if (UserRole.findByUserAndRole(User.findByUsername(username), Role.findByAuthority('ROLE_ADMINISTRATOR')))
        {
            projectList = Project.findAll("from Project order by modifiedDate desc", [max: params.max ?: 10, offset: params.offset ?: 0])
            count = Project.executeQuery("select count(id) from Project")
        }
        else
        {
            projectList = Project.findAll("from Project where user.username = '${username}' order by modifiedDate desc", [max: params.max ?: 10, offset: params.offset ?: 0])
            count = Project.executeQuery("select count(id) from Project where user.username = '${username}' ")
        }

        params.max = Math.min(max ?: 10, 100)
        respond projectList, model: [projectCount: Project.count()]
    }

    def show(Project project)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def workflowInstanceList = WorkflowInstance.findAll("from WorkflowInstance where project.id = ?", [project.id])
        def attachmentList = Attachment.findAll("from Attachment where project.id = ?", [project.id])
        def appointmentList = Activity.findAll("from Activity where project.id = ? and type.id = ?", [project.id, ActivityType.find("from ActivityType where name = 'Appointment'")?.id])
        def taskList = Activity.findAll("from Activity where project.id = ? and type.id = ?", [project.id, ActivityType.find("from ActivityType where name = 'Task'")?.id])
        def noteList = Note.findAll("from Note where project.id = ?", [project.id])
        def teamList = ProjectTeam.findAll("from ProjectTeam where project.id = ?", [project.id])
        def issueList = Issue.findAll("from Issue where project.id = ?", [project.id])

        respond project, model: [workflowInstanceList: workflowInstanceList, attachmentList: attachmentList, appointmentList: appointmentList, taskList: taskList, noteList: noteList, teamList: teamList, issueList: issueList, teamName: 'projectTeam']
    }

    def create()
    {
        respond new Project(params)
    }

    @Transactional
    def save(Project project)
    {
        if (project == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (project.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond project.errors, view: 'create'
            return
        }

        project.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'project.label', default: 'Project'), project.id])
                redirect project
            }
            '*' { respond project, [status: CREATED] }
        }
    }

    def edit(Project project)
    {
        respond project
    }

    @Transactional
    def update(Project project)
    {
        if (project == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (project.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond project.errors, view: 'edit'
            return
        }

        project.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'project.label', default: 'Project'), project.id])
                redirect project
            }
            '*' { respond project, [status: OK] }
        }
    }

    @Transactional
    def delete(Project project)
    {

        if (project == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        project.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'project.label', default: 'Project'), project.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'project.label', default: 'Project'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def searchProject()
    {
        def username = springSecurityService?.getPrincipal()?.username
        String name = params["name"]

        String sql = "from Project where 1 = 1"
        if (!UserRole.findByUserAndRole(User.findByUsername(username), Role.findByAuthority('ROLE_ADMINISTRATOR')))
        {
            sql += " and user.username='${username}'"
        }
        if (name)
        {
            sql += " and name like '%${name}%'"
        }

        String countSql = "select count(id) " + sql
        sql += " order by modifiedDate desc"

        def projectList = Project.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = Project.executeQuery(countSql)

        respond projectList, model: [projectCount: count[0], params: params], view: 'index'
    }
}
